<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="批次名称" prop="batchName">
          <el-input v-model="queryParams.batchName" placeholder="批次名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" size="default" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" size="default" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" plain size="default" :disabled="!selections.length" @click="withdraw()">
            批量撤回
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="app-content">
      <el-table v-loading="loading" :data="recordList" highlight-current-row border height="calc(100vh - 330px)"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="batchId" label="批次ID" width="90"></el-table-column> -->
        <el-table-column prop="batchName" label="批次名称" min-width="140"></el-table-column>
        <!-- <el-table-column prop="companyId" label="填报单位ID" width="120"></el-table-column> -->
        <el-table-column prop="companyName" label="填报单位名称" min-width="240" show-overflow-tooltip></el-table-column>
        <el-table-column prop="energyType" label="发电类型" width="100"></el-table-column>
        <!-- 0-草稿 1-已提交 -->
        <el-table-column prop="submitStatus" label="填报状态" width="100">
          <template #default="scope">
            <el-tag :type="submitTag[scope.row.submitStatus]">
              {{ submitMap[scope.row.submitStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 0-未审核 1-通过 2-不通过 -->
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="auditTag[scope.row.auditStatus]">
              {{ auditMap[scope.row.auditStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="batchEndTime" label="批次截止时间" width="170"></el-table-column>
        <el-table-column prop="rejectReason" label="不通过原因" min-width="120"></el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="170"></el-table-column>
        <!-- <el-table-column prop="auditUserId" label="审核用户ID" width="120"></el-table-column> -->
        <el-table-column prop="submitTime" label="提交时间" width="170"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120"></el-table-column>
        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope">
            <el-button v-if="scope.row.submitStatus == 1 && scope.row.auditStatus != 1" link type="danger" size="small"
              @click="withdraw(scope.row.id)">
              撤回
            </el-button>
            <el-button link type="primary" size="small" @click="goDetail(scope.row)">
              <!-- 草稿&&待审核/不通过可以填报 -->
              {{
                !isDeadLineDate(scope.row) &&
                  scope.row.submitStatus == 0 &&
                  scope.row.auditStatus != 1
                  ? '填报'
                  : '查看'
              }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="queryParams.total > 0" class="pager-container">
        <pagination v-model:total="queryParams.total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="handlePagination" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'UserList',
  inheritAttrs: false,
});

import BatchAPI from '@/api/batch/batch.api';
import RecordApi from '@/api/batch/record.api';
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute(); // 获取路由参数
const router = useRouter(); // 路由跳转

const queryFormRef = ref();
const queryParams = reactive<{
  total: number;
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}>({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});

// 0-草稿 1-已提交 2-已撤回
const submitTag = reactive<any>({
  0: 'primary',
  1: 'success',
  2: 'danger',
});
const submitMap = reactive<any>({
  0: '草稿',
  1: '已提交',
  2: '撤回',
});
// 0-未审核 1-通过 2-不通过
const auditTag = reactive<any>({
  0: 'warning',
  1: 'success',
  2: 'danger',
});
const auditMap = reactive<any>({
  0: '未审核',
  1: '通过',
  2: '不通过',
});
const loading = ref(false);
const recordList = ref<any>([]);
// 选中的记录ID
const selections = ref<any[]>([]);

const handleQuery = () => {
  loading.value = true;
  const params = {
    current: queryParams.pageNum,
    size: queryParams.pageSize,
    batchName: queryParams.batchName,
  };
  RecordApi.getRecordPageByUser(params)
    .then((data: any) => {
      recordList.value = [...data.records];
      queryParams.total = data.total;
      loading.value = false;
    })
    .catch((err) => {
      console.error(err);
      loading.value = false;
    });
};
const handleReset = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.batchName = undefined;
  handleQuery();
};
const handlePagination = () => {
  handleQuery();
};
const handleSelectionChange = (selection: any[]) => {
  selections.value = [...selection];
};

const withdraw = (recordId?: any) => {
  if (!recordId) {
    console.log('selections.value', selections.value);
    for (let i = 0; i < selections.value.length; i++) {
      const item: any = selections.value[i];
      if (item.submitStatus != 1 || item.auditStatus != 0) {
        ElMessage({
          type: 'warning',
          message: '只有已提交且未审核的记录才能撤回',
        });
        return;
      }
    }
  }
  let msg = recordId ? '' : '批量';
  ElMessageBox.confirm(`确认${msg}撤回?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      if (recordId) {
        RecordApi.withdrawRecord(recordId)
          .then(() => {
            ElMessage({
              type: 'success',
              message: '撤回成功',
            });
            handleQuery();
          })
          .catch(() => { });
        return;
      } else {
        const ids = selections.value.map((item: any) => item.id);
        RecordApi.batchWithdrawRecord(ids)
          .then(() => {
            ElMessage({
              type: 'success',
              message: '批量撤回成功',
            });
            queryParams.pageNum = 1;
            handleQuery();
          })
          .catch(() => { });
      }
    })
    .catch(() => { });
};

const goDetail = (row: any) => {
  router.push({
    path: '/batch/fill',
    query: {
      batchId: row.batchId, // 批次id
      recordId: row.id, // 记录id
      // status: row.submitStatus, // 填报状态
      // checkStatus: row.auditStatus, // 审核状态
    },
  });
};
function isDeadLineDate(row: any) {
  const date = new Date(row.batchEndTime);
  const nowDate = new Date();
  return date < nowDate;
}
onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped></style>
